import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:t2app/src/common/Tool.dart';
import 'package:t2app/src/util/log_util.dart';

class HttpRequest {

  static final Dio dio = Dio(BaseOptions(
    connectTimeout: const Duration(seconds: 5)
  ));

  static final HttpRequest _httpRequest = HttpRequest._internal();

  HttpRequest._internal(){
    //...
  }

  factory HttpRequest(){
    return _httpRequest;
  }

  request(String url, {
    String method = HttpRequestMethod.GET,
    Map<String, dynamic>? params,
    Map<String, dynamic>? data,
    Function? success,
    Function? error
  }) async {
    // 1.创建单独配置
    final options = Options(method: method);
    // 2.发送网络请求
    try {
      LogUtil.p("http:request:params:" + params.toString());
      LogUtil.p("http:request:data:" + data.toString());
      Response response = await dio.request(
          url, queryParameters: params, data: data,  options: options);
      if (success != null) {
        Map<String, dynamic> result = jsonDecode(jsonEncode(response.data));
        LogUtil.p("http:response:" + result.toString());
        if (result["code"] != 1) {
          Tool.EasyLoading_Error(result["msg"]);
        } else {
          success(result);
        }
      }
    } on DioException catch (e) {
      LogUtil.e(e);
      if (error != null) {
        error(e);
      } else {
        Tool.EasyLoading_Error("接口服务异常");
      }
    }
  }
}

class HttpRequestMethod{
  static const String POST = "post";
  static const String GET = "get";
}
